<template>
  <p-modal
      v-model="visible"
      :title="'选择物料'"
      :width="1300"
    >
      <div style="display:flex;align-items: center;">
        <div style="width:240px;">
          <p-input-search
            allow-clear
            v-model="keyword"
            :placeholder="'请输入物料编码或名称'"
          />
        </div>
        <p-button
          type="primary"
          style="margin-left:10px;"
          @click="search"
        >
          搜索
        </p-button>
      </div>
      <p-table
        v-if="tableFlag"
        ref="tableRef"
        :data-source="tableData"
        :columns="curCols"
        :pagination="pagination"
        :scroll="{ y: 400, x: 1200 }"
        row-key="mcode"
         @change="tableChange"
        style="width: 100%;margin-top:16px;"
        :row-selection="{ getCheckboxProps:getCheckboxProps,selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      >
        <span slot="maintenanceKey" slot-scope="text, record">
           <p-switch @change="switchChange" v-model="record.maintenanceKey" checked-children="是" un-checked-children="否" default-checked />
        </span>
        <span slot="maintenanceSap" slot-scope="text, record">
           {{$parent.maintenanceSapMap[record.maintenanceSap]}}
        </span>
        <span slot="stationsRequired" slot-scope="text, record, index">
          <p-tooltip :overlayClassName="'overlayClassName'" :visible="record.stationsRequired > (record.remainQuantityOrigin + record.stationsRequiredOrigin)">
            <template slot="title">
              不能超过可用数量
            </template>
            <p-input-number
              :formatter="formatter"
              :parser="parserValue"
              @change="stationsRequiredChange(record)"
              :min="0"
              :class="{errorClass: record.stationsRequired > (record.remainQuantityOrigin + record.stationsRequiredOrigin)}"
              :disabled="record.remainQuantityOrigin + record.stationsRequiredOrigin === 0"
              :max="record.remainQuantityOrigin + record.stationsRequiredOrigin"
              v-model="tableData[index].stationsRequired"
            />
          </p-tooltip>
        </span>
      </p-table>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <div class="cText">
          <span>已选择({{ chooseList.length }})</span>
        </div>
        <div class="modal-footer-scroll">
          <p-tag
            v-for="item in chooseList"
            :key="item.mcode"
            closable
            size="mini"
            style="margin-right:10px;"
            @close="removeChoose(item.mcode)"
          >
            {{ item[tagName] || '' }}
          </p-tag>
        </div>
        <p-button
          type="primary"
          @click="confirmChoose"
        >
          确 定
        </p-button>
      </div>
      </p-dialog>
    </p-modal>
</template>

<script>
import { cloneObject } from '@u/util'
import { userList } from '@/api/manage'
import mesPeProcess from "@/api/mesPeProcess";
import mixins from './mixins'
import _ from "lodash";
export default {
  name: 'ChooseCon',
  mixins: [mixins],
  props: {
    x: {
      type: Number,
      default: () => {
        return 0;
      }
    },
    tagName: {
      type: String,
      default: () => {
        return 'name';
      }
    },
    title: String,
    columns: Array,
  },
  data () {
    return {
      searchDept: '',
      tableFlag: true,
      orgOptions: [],
      emptyText: '请选择',
      chooseList: [],
      selectedRowKeys: [],
      maintenanceKeyList: [
        {
          value: '1',
          label: '是',
        },
        {
          value: '2',
          label: '否',
        },
      ],
      visible: false,
      keyword: '',
      curCols: [],
      tableDataCopy: [],
      pagination: {
        current: 1,
        total: 0,
        pageSize: 10, // 每页中显示10条数据
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'], // 每页中显示的数据
        showTotal: total => `共 ${total} 条` // 分页中显示总的数据
      },
      tableData: [],
      tableDataMock: [
        {
          allQuantity: 2,
          bomGroup: "A",
          bomLevel: 1,
          id: null,
          maintenanceKey: "0",
          maintenanceSap: "0",
          mcode: "O50120190148",
          mexplain: "qwert",
          mname: "名称TestBom02_01",
          remainQuantity: 2,
          sprc: "QWERT",
          stationId: null,
          stationsRequired: null,
          unit: null,
          workstationCode: null,
          workstationName: null,
        },
        {
          allQuantity: 2,
          bomGroup: "A",
          bomLevel: 1,
          id: null,
          maintenanceKey: "0",
          maintenanceSap: "0",
          mcode: "O50100030189",
          mexplain: "qwert",
          mname: "名称TestBom02_02",
          remainQuantity: 2,
          sprc: "QWERT",
          stationId: null,
          stationsRequired: null,
          unit: null,
          workstationCode: null,
          workstationName: null,
        }
      ],
    }
  },
  computed: {
    form(){
      return this.$parent.$parent.$parent.$refs.BaseInfo.form;
    },
    workstationCode(){
      return this.$parent.$parent.curSelectedNodes.processmcode;
    },
    productCode(){
      return this.$parent.$parent.$parent.$refs.BaseInfo.form.productCode;
    },
    /* curPens(){
      return this.$parent.$parent.canvas.data.pens;
    }, */
  },
  watch:{
    visible(val){
      if(val){
        this.tableData = _.cloneDeep(this.tableDataCopy);
        this.recoverChoose(this.tableData);
        // 计算当前剩余当前工站物料可用数量
        this.calcuRemainQuantity(this.tableData);
        // 过滤掉可用数量为0的数据 并且不属于自己可用的
        console.log(
          '过滤掉可用数量为0的数据 并且不属于自己可用的', 
          this.tableData.filter( el => el.remainQuantityOrigin + el.stationsRequiredOrigin === 0)
        );
        this.tableData = this.tableData.filter( el => {
          return el.remainQuantityOrigin + el.stationsRequiredOrigin > 0
        });
        this.pagination.total = this.tableData.length;
        // 拷贝一份数据 作为搜索用
        this.copyTableData();
      }
    },
    // 工站发生变化时 重新调用接口获取可选择的工序BOM
    workstationCode(val){
      this.queryAllBomInfo();
    },
    // 产品编码发生变化时 重新调用接口获取可选择的工序BOM
    productCode(val){
      this.queryAllBomInfo();
    },
    selectedRowKeys(val){
      this.chooseList = this.tableDataCopy.filter(item => this.selectedRowKeys.includes(item.mcode));
    },
  },
  mounted () {
    this.curCols = this.getCols();
    this.queryAllBomInfo();
  },
  methods: {
    formatter(value){
      let str = value;
      if (value){
        str =  `${value}`.replace(/\D*/g, '');
      }else {
        str = 0;
      }
      return str;
    },
    parserValue(value){
      let str = value;
      if (value){
        str =  `${value}`.replace(/\D*/g, '');
      }else {
        str = 0;
      }
      return str;
    },
    copyTableData(){
      this.tableDataCopy = _.cloneDeep(this.tableData);
    },
    replaceSomeTableData(){
      this.tableDataCopy.forEach( (ele, index) =>{
        this.tableData.forEach( el =>{
          if ( ele.mcode === el.mcode ){
            this.tableDataCopy[index] = _.cloneDeep(el);
          }
        });
      });
    },
    getCheckboxProps: record => ({
      props: {
        disabled: record.stationsRequired === 0, // Column configuration not to be checked
      },
    }),
    recoverChoose(data){
      const curData = [];
      // 结合外面的已选中的，以选中的为准
      data.forEach( (el, index) =>{
        curData[index] = el;
        this.$parent.options.forEach( e =>{
          if( el.mcode === e.mcode ){
            curData[index] = _.cloneDeep(e);
            // this.$set(this.tableData, index, _.cloneDeep(e));
          }
        });
        if ( curData[index].maintenanceKey === 1 || curData[index].maintenanceKey === true ){
          curData[index].maintenanceKey = true;
        }else {
          curData[index].maintenanceKey = false;
        }
      });
      // 结合其他节点计算更新当前tableData todo
      this.tableData = curData;
    },
    // 计算当前剩余当前工站物料可用数量
    calcuRemainQuantity(curData){
      const that = this;
      let processbomAllMap = this.calcProcessbomAllMap();
      curData.forEach( el =>{
        if (processbomAllMap[el.mcode]){
          // 物料可用数量 = 总数量 - 所有已分配给工站的数量
          let allStationsRequired = processbomAllMap[el.mcode].map( el => el.stationsRequired );
          if ( allStationsRequired.length > 0 ){
            allStationsRequired = allStationsRequired.reduce((total, num) => (total + num));
          }else {
            allStationsRequired = 0;
          }
          el.remainQuantity = el.allQuantity - allStationsRequired;
          el.remainQuantityOrigin = el.remainQuantity;
          el.allStationsRequired = allStationsRequired;
        }
      });
    },
    queryAllBomInfo(){
      const that = this;
      mesPeProcess.queryAllBomInfo({
        productCode: this.form.productCode,
        routerCode: this.form.routeCode,
        version: this.form.version,
        workstationCode: this.workstationCode,
       /*  productCode: '2945769R1A' || this.form.productCode,
        routerCode: '2945769R1A-1' || this.form.routeCode,
        version: '2945769R1A-20200901-123' || this.form.version,
        workstationCode: 'TBM01' || this.workstationCode, */
      }).then( res =>{ 
        if (res.code === 0){
          const curData = res.data || [];
          // const curData = that.tableDataMock;
          curData.forEach( el =>{
            // 实时时的工站所需数量
            el.stationsRequired = el.stationsRequired || 0;
            // 未修改时的工站所需数量
            el.stationsRequiredOrigin = el.stationsRequired;
            // 未修改时的工站可用数量
            el.remainQuantityOrigin = el.remainQuantity;
            // 当前物料被分配给所有的工站的数量
            el.allStationsRequired = el.allStationsRequired || 0;
            el.maintenanceSap = el.maintenanceSap ? 2 : 1; 
            // 是否关键物料 1 关键 2 不关键
            el.maintenanceKey = el.maintenanceKey === 1 ? true : false;
            // el.id = el.mcode;
          });
          // 结合外面的已选中的，以选中的为准
          this.recoverChoose(curData);
          // 计算当前剩余当前工站物料可用数量
          this.calcuRemainQuantity(curData);
          this.tableData = curData;
          // this.pagination.total = this.tableData.length;
          // 拷贝一份数据 作为搜索用
          this.copyTableData();
        }
      });
    },
    switchChange(){
      this.replaceSomeTableData();
    },
    stationsRequiredChange(row){
      const stationsRequiredOrigin = row.stationsRequiredOrigin;
      row.remainQuantity = ( row.allQuantity - (row.allStationsRequired - stationsRequiredOrigin) ) - row.stationsRequired;
      // 数量大于1 自动选中 等于0 自动取消选中
      if(row.stationsRequired > 0){
        if(!this.selectedRowKeys.includes(row.mcode)){
          this.selectedRowKeys.push(row.mcode);
        }
      }else {
        if(this.selectedRowKeys.includes(row.mcode)){
          this.selectedRowKeys = this.selectedRowKeys.filter( el => el !== row.mcode );
        } 
      }
      this.replaceSomeTableData();
      this.tableData.splice();
      console.log(row.stationsRequired);
    },
    getCols(){
      let cols = _.cloneDeep(this.columns);
      cols = cols.slice(0, cols.length - 1);
      const index1 = cols.findIndex( el => el.dataIndex === 'stationsRequired' );
      cols[index1].scopedSlots = { customRender: 'stationsRequired' };
      return cols;
    },
    onSelectChange(selectedRowKeys, selectedRows){
      this.selectedRowKeys = selectedRowKeys;
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows)
    },
    tableChange (pageOptions) {
      console.log(this.selectedRowKeys);
      this.pagination.current = pageOptions.current;
      this.pagination.pageSize = pageOptions.pageSize;
      const startIndex = (pageOptions.current - 1)*pageOptions.pageSize;
      this.tableData = this.tableDataCopy.slice(startIndex, startIndex + pageOptions.pageSize)
    },
    search () {
      // this.currentPage = 1
      /* this.$parent[this.apiMethods]({
        pageNo: this.currentPage,
        limit: this.pagination.pageSize,
        keyword: this.keyword,
      }); */
      this.pagination.current = 1;
      this.tableData = this.tableDataCopy.filter( el =>{
        const mcode = this.keyword || el.mcode || '';
        const mname = this.keyword || el.mname || '';
        return (el.mcode || '').includes(mcode) || (el.mname || '').includes(mname);
      });
    },
    removeChoose (mcode) {
      this.selectedRowKeys = this.selectedRowKeys.filter( el => el !== mcode);
    },
    confirmChoose () {
      this.chooseList = this.tableDataCopy.filter(item => this.selectedRowKeys.includes(item.mcode));
      // 计算所有的工站可分配的数量
      this.visible = false;
      const arr = _.cloneDeep(this.chooseList);
      arr.forEach(el => el.maintenanceKey = el.maintenanceKey === true ? 1 : 2 );
      
      this.$emit('confirm', arr)
    }
  }
}
</script>

<style scoped lang="less">
.choose-items-con {
  border: solid 1px #DEDEDF;
  border-radius: 4px;
  box-sizing: border-box;
  color: #606266;
  transition: border-color .2s;
  display: flex;
  width: 100%;
  cursor: pointer;
  &:hover {
      border-color: #C0C4CC;
  }
  .tags{
      width:calc(100% - 25px);
      max-height: 160px;
      overflow-y: auto;
      padding-left: 15px;
  }
  .empty{
    opacity:0.6;
  }
  .icon{
      width:25px;
      cursor: pointer;
      transition: transform .3s;
      text-align: center;
      &.active{
          transform: rotate(180deg);
      }
  }
}

.dialog-footer{
  display:flex;
  align-items:center;
  .cText{
    word-break: keep-all;
    white-space: nowrap;
  }
}

.modal-footer-scroll {
    width: 100%;
    text-align: left;
    overflow-x: auto;
    overflow-y: hidden;
    white-space: nowrap;
    margin:0 16px;
    padding: 6px 0;
}
.select-down .a-select-dropdown__item{
  padding:0;
}
.errorClass{
  border-color: rgba(245, 117, 117, 0.9);
}

</style>
<style lang="less">
.overlayClassName{
  .poros-tooltip-inner{
    background-color: rgba(245, 117, 117, 0.9);
  }
  .poros-tooltip-arrow::before{
    background-color: rgba(245, 117, 117, 0.9);
  }
}
</style>
